package com.pudu.mydemo.entity;

/**
 * Created by lgq on 2016/7/13.
 */

import android.content.Context;
import android.util.Log;

import com.pudu.mydemo.utils.ClientConnectUtils;
import com.pudu.mydemo.utils.ConstantUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

/**
 * 服务端线程,用来作为广播
 */
public class ServerThread implements Runnable{

    private MulticastSocket multicastSocket;
    private InetAddress serverAddress;

    // 需要广播出去的重要信息,比如服务端的局域网IP,或动态获得IP.下面介绍.
    private String ip = "192.168.137.60";
    private Context context;

    public ServerThread(Context context){
        this.context = context;
    }

    @Override
    public void run() {

        try {
            multicastSocket = new MulticastSocket(ConstantUtils.MULTICAST_PORT);
            serverAddress = InetAddress.getByName(ConstantUtils.GROUP_IP);

            // 将该MulticastSocket对象加入到指定的多点广播地址,
            // MulticastSocket使用public void joinGroup(InetAddress mcastaddr)
            // throws IOException方法加入指定组.
            	multicastSocket.joinGroup(serverAddress);

            //获取本地ip地址
            ip = ClientConnectUtils.getlocalip(context);
            // 将要广播出去的数据转为byte类型

            byte data[] = ip.getBytes();
            DatagramPacket dp = new DatagramPacket(data, data.length,
                    serverAddress, ConstantUtils.MULTICAST_PORT);

            // 调用MulticastSocket对象的send方法 发送数据
            while (true) {
                Log.i("lgq", "while send");
                multicastSocket.send(dp);
                Thread.sleep(5000);
            }
            // 如果不想再接收,广播数据,可以采用 public void leaveGroup(InetAddress
            // mcastaddr) throws IOException
            // multicastSocket.leaveGroup(serverAddress);
        } catch (IOException e) {
            e.printStackTrace();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
